﻿using AutoMapper;
using B.S.DataBase.SuY.Read.Api.AutoList.Command;
using B.S.DataBase.SuYuan.Domain.Model;
using B.S.DataBase.SuYuan.ErrorCode;
using B.S.DataBase.SuYuan.Infrastructrue.Interface;
using MediatR;

namespace B.S.DataBase.SuY.Read.Api.AutoList.CommandHarder
{
    public class AddGoodsCommandHarder : IRequestHandler<AddGoodsCommand, ApiReslit<object>>
    {

        private readonly IMapper mapper;
        private readonly IBaseRepository<Goods> repository;

        public AddGoodsCommandHarder(IMapper mapper, IBaseRepository<Goods> repository)
        {
            this.mapper = mapper;
            this.repository = repository;
        }

        public Task<ApiReslit<object>> Handle(AddGoodsCommand request, CancellationToken cancellationToken)
        {
            ApiReslit<object> result = new ApiReslit<object>();
           
            var xi = repository.GetAll().Result.Where(x => x.G_batch == request.G_batch).FirstOrDefault();
            var kk = repository.GetAll().Result.Where(x => x.G_License == request.G_License).FirstOrDefault();
            if (xi != null)
            {
                result.Code = ApiEnum.添加失败;
                result.Msg = "生产批次重复";
                return Task.FromResult(result);

            }
            if (kk != null)
            {
                result.Code = ApiEnum.添加失败;
                result.Msg = "生产许可证重复";
                return Task.FromResult(result);

            }
            var model = mapper.Map<Goods>(request);
            model.CreateTime = DateTime.Now;
            model.Refine = "10%";
            var list= repository.Add(model).Result;
            if (list > 0)
            {
                result.Code = ApiEnum.添加成功;
                result.Msg = ApiEnum.添加成功.ToString();
            }
            else {
                result.Code = ApiEnum.添加失败;
                result.Msg = ApiEnum.添加失败.ToString();
            }


            return Task.FromResult(result);

        }
    }
}
